package com.changgou.system.filter;

import com.changgou.system.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1、获取请求
        ServerHttpRequest request = exchange.getRequest();
        //2、获取响应
        ServerHttpResponse response = exchange.getResponse();
        //3、判断是否是登录请求，如果是登录请求，放行
        if (request.getURI().getPath().contains("/admin/login")){
            //登录请求，放行
            return chain.filter(exchange);
        }
        //4、获取请求头
        HttpHeaders headers = request.getHeaders();
        //5、请求头中获取令牌
        String token = headers.getFirst("token");
        //6、判断请求头中是否有令牌
        if (StringUtils.isEmpty(token)){
            //token为空， 不存在令牌
            //6.1、请求头中的没有令牌，则返回错误页面
            //响应中放入返回的状态码，没有权限访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回
            return response.setComplete();
        }
        //6.2、请求头中有令牌，进行令牌的解析
        try {
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            //6.2.1、若解析失败，返回错误页面
            // jwt令牌 错误，解析失败 解析jwt令牌出错, 说明令牌过期或者伪造等不合法情况出现
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //6.2.2、解析成功，放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
